﻿open System
open Ochkin.SquaredSoccer.Base

let game = new Match(5, 3, false, GameStyle.Random)

while game.GameState = GameState.Default do
    let rec loopUserMove () =
        Console.Write("Your move:>\t")
        let userMoves = Console.ReadLine()
        let getDir = function
            | '8' -> Some (Direction.Simple North)
            | '9' -> Some (Direction.Mix (North, East))
            | '6' -> Some (Direction.Simple East)
            | '3' -> Some (Direction.Mix (South, East))
            | '2' -> Some (Direction.Simple South)
            | '1' -> Some (Direction.Mix (South, West))
            | '4' -> Some (Direction.Simple West)
            | '7' -> Some (Direction.Mix (North, West))
            | _ -> None
        let userDirs = seq {for ch in userMoves -> getDir ch}
        if Seq.exists (fun (item: Direction option) -> item.IsNone) userDirs then
            printfn "Invalid direction. Please, enter numbers from 1 to 9."
            loopUserMove()
        else
            if not (userDirs |> Seq.map (fun item -> item.Value) |> game.MakeHumanMove) then
                printfn "%A" (String.Concat ("Failed to make the move (", userMoves, ")."))
                loopUserMove()
    loopUserMove ()
    if game.GameState = GameState.Default then
        Console.Write ("Computer's move:\t")
        let result = game.GetComputerMove ()        
        if result.IsSome then
            let toChar = function
                | Direction.Simple North -> '8'
                | Direction.Mix (North, East) -> '9'
                | Direction.Simple East -> '6'
                | Direction.Mix (South, East) -> '3'
                | Direction.Simple South -> '2'
                | Direction.Mix (South, West) -> '1'
                | Direction.Simple West -> '4'
                | Direction.Mix (North, West) -> '7'
                | _ -> failwith "Argument is out of range."
            result.Value |> Seq.map toChar |> Seq.iter Console.Write
        else
            Console.Write("Impossible to make computer's move.")
        Console.WriteLine()

let resultMessage =
    match game.GameState with
        | GameState.Default -> "The game was incorrectly interrupted."
        | GameState.Won (Human) -> "Human won."
        | GameState.Won (Computer) -> "Computer won."
        | GameState.Tie -> "Tie."
Console.WriteLine("\nGame result: "+resultMessage)